from django.shortcuts import render, redirect
from django.urls import reverse
from user.views import auth
from django.http import JsonResponse
from .models import ChatRecord, Img
import datetime, time
from Online_Response_System.config.base import host
import uuid
import hashlib


# 生成合法的时间，解决不在1970-2038年之间的时间戳会报错
def make_vaild_time(origin_time: float, default: float):
    _now = time.time()
    # 检查时间有没有超过当前时间
    origin_time = origin_time if not origin_time or origin_time < _now else default
    return datetime.datetime.fromtimestamp(origin_time)


# 高频短语
@auth(True)
def get_high_rate_words(request):
    if request.method == 'GET':
        start_time = make_vaild_time(float(request.GET.get('start_time')), 0)
        end_time = make_vaild_time(float(request.GET.get('end_time')), time.time())

        data, data_path = ChatRecord.get_high_rate_words(start_time, end_time)

        return JsonResponse({
            'code': '200',
            'msg': '响应成功!',
            'data': {
                'wordcloud_link': f'{host}{data_path}',
                'data': data,

            }
        })


# 图片上传服务
@auth()
def upload(request):
    if request.method == 'POST':
        img = request.FILES.get('img')

        # 限制文件大小2M
        if img.size > 2000 * 1024:
            return JsonResponse(
                {'code': '400',
                 'msg': '上传失败,图片最大支持2M！',
                 }
            )

        # 限制文件类型
        for suffix in ['.jpg', '.png', '.gif']:
            if img.name.endswith(suffix):
                break
        else:
            return JsonResponse(
                {'code': '400',
                 'msg': '上传失败,支持的图片格式为:jpg,png,gif！',
                 }
            )

        # 基于时间戳的uuid，防止文件重名
        uid = uuid.uuid1()
        filename_list = img.name.rsplit('.', 1)
        filename_list.insert(1, uid.hex)
        img.name = '.'.join(filename_list)

        new_img = Img(uploader=request.user, img=img)
        new_img.save()

        return JsonResponse(
            {'code': '200',
             'msg': '上传成功！',
             'url': f'{host}media/{new_img.img}'
             }
        )


# chat/views.py
@auth()
def index(request):
    if request.method == 'POST':
        # 获取聊天对象
        chat_target = request.POST.get('chat-target')
        # 根据自己的用户名和聊天对象的用户名生成一个唯一的房号
        room_name = hashlib.md5(bytes(str(sorted([request.user.username , chat_target])), "utf-8")).digest().hex()
        return redirect(reverse('chat:room', kwargs={'room_name': room_name,'chat_target':chat_target}))

    if request.method == 'GET':
        return render(request, 'chat/index.html')


@auth()
def room(request, room_name,chat_target):


    return render(request, 'chat/room.html', {
        'room_name': room_name,
        'username': request.user.username,
        'chat_target': chat_target,
    })
